package com.co.vote.web.controller.user;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.co.common.utils.MD5;
import com.co.server.constant.Constant;
import com.co.server.entity.user.TUserActive;
import com.co.server.entity.user.TUserLogin;
import com.co.server.entity.user.TUsers;
import com.co.server.entity.user.aide.TUsersConstant;
import com.co.server.service.user.TUserActiveService;
import com.co.server.service.user.TUserLoginService;
import com.co.server.service.user.TUsersService;
import com.co.server.service.user.impl.UsersSession;
import com.co.vote.constant.CookieConstant;
import com.co.vote.constant.HttpStatusCode;
import com.co.vote.constant.SessionConstant;
import com.co.vote.utils.ClientUtil;
import com.co.vote.utils.CookieUtil;
import com.co.vote.utils.PathUtil;
import com.co.vote.utils.SessionUtil;



@Controller
public class LoginController {
	
	@Resource
	private TUsersService tUsersService;
	@Resource
	private TUserLoginService tUserLoginService;
	@Resource
	private TUserActiveService tUserActiveService;
	
	@RequestMapping(value="/loginInit",method = { RequestMethod.GET})
	public String loginInit(){
		return "user/loginInit";
	}
	
	@ResponseBody
	@RequestMapping(value = "/login")
	public Map<String,Object> login(HttpServletRequest request,HttpServletResponse response,HttpSession session,
			String username,String password,String identifyCode,boolean rememberMe){
		
		Map<String,Object> mapResult = new HashMap<String,Object>();

		UsersSession oldUsersSession  = SessionUtil.getUserSession(session);
		String identifyCodeSession  = (String)session.getAttribute(SessionConstant.SESSION_IDENTITY_CODE);

		if(identifyCodeSession != null){
			//开始验证登录
			if (StringUtils.isBlank(identifyCode) || !identifyCodeSession.equals(identifyCode.toUpperCase())) {
				final int CODE_ERROR_IDENTITY = 401;
				mapResult.put("code",CODE_ERROR_IDENTITY);
				mapResult.put("desc", "验证码错误!");
				return mapResult;
			} else {
				session.removeAttribute(SessionConstant.SESSION_IDENTITY_CODE);
			}
		}
		
		//查询用户
		if (StringUtils.isBlank(username)) {
			mapResult.put("code", HttpStatusCode.CODE_ERROR);
			mapResult.put("desc", "用户名不能为空!");
			return mapResult;
		}
		
		if (StringUtils.isBlank(password)) {
			mapResult.put("code", HttpStatusCode.CODE_ERROR);
			mapResult.put("desc", "密码不能为空!");
			return mapResult;
		}
		
		TUsers tUsers = tUsersService.queryByLoginName(username);
		
		//密码加密
		String passwordMd5 = MD5.encodeStr(password);
		if (tUsers == null || !tUsers.getUserPassword().equals(passwordMd5)) {
			mapResult.put("code", HttpStatusCode.CODE_ERROR);
			mapResult.put("desc", "用户名或密码错误!");
			return mapResult;
		} else if (tUsers.getStatus() == Constant.STATUS_NOT_ACTIVE) {
			mapResult.put("code", HttpStatusCode.CODE_ERROR);
			mapResult.put("desc", "用户已被锁定!");
			return mapResult;
		} else {
			// 清空验证码
			session.removeAttribute(SessionConstant.SESSION_IDENTITY_CODE);
			//用户登录
			tUsersService.updateLogin(oldUsersSession,tUsers,ClientUtil.getIp(request));
			
			//判断该用户是否启用自动登录
			if(rememberMe){
				//添加用户到自动登录
				String uuid = UUID.randomUUID().toString();
				TUserLogin tUserLogin = new TUserLogin();
				tUserLogin.setLoginIp(tUsers.getLastIp());
				tUserLogin.setRememberKey(uuid);
				tUserLogin.setUserId(tUsers.getUserId());
				tUserLogin.setLoginTime(new Date());
				tUserLoginService.add(tUserLogin);
				CookieUtil.addCookieDefaultAge(response, CookieConstant.COOKIE_USER_KEY, uuid);
			}
			mapResult.put("code", HttpStatusCode.CODE_SUCCESS);
			//登录跳转
			String url = (String)session.getAttribute(SessionConstant.SESSION_BACK_URL);
			if(StringUtils.isBlank(url)){
				url = PathUtil.getBasePath(request);
			}
			mapResult.put("url", url);
			session.removeAttribute(SessionConstant.SESSION_BACK_URL);
			session.setAttribute(SessionConstant.SESSION_USER, oldUsersSession);
		}
		return mapResult;
	}
	@ResponseBody
	@RequestMapping(value = "/loginGuest")
	public Map<String,Object> loginGuest(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		
		Map<String,Object> mapResult = new HashMap<String,Object>();
		UsersSession oldUsersSession  = (UsersSession)session.getAttribute(SessionConstant.SESSION_USER);
		
		TUsers guest = tUsersService.queryById(TUsersConstant.USER_GUEST_ID);
		if (oldUsersSession.isLogin()) {
			mapResult.put("code", HttpStatusCode.CODE_TIP_ONE);
			mapResult.put("desc", "您已经登录");
			return mapResult;
		} else if (guest.getStatus() == Constant.STATUS_NOT_ACTIVE) {
			mapResult.put("code", HttpStatusCode.CODE_ERROR);
			mapResult.put("desc", "用户已被锁定!");
			return mapResult;
		} else {
			//游客登录
			tUsersService.updateLogin(oldUsersSession,guest,ClientUtil.getIp(request));
			mapResult.put("code", HttpStatusCode.CODE_SUCCESS);
			//登录跳转
			String url = (String)session.getAttribute(SessionConstant.SESSION_BACK_URL);
			if(StringUtils.isBlank(url)){
				url = PathUtil.getBasePath(request);
			}
			mapResult.put("url", url);
			session.removeAttribute(SessionConstant.SESSION_BACK_URL);
			session.setAttribute(SessionConstant.SESSION_USER, oldUsersSession);
		}
		return mapResult;
	}
	
	@RequestMapping(value="/logout",method = { RequestMethod.GET})
	public String logout(HttpServletRequest request,HttpServletResponse response,HttpSession session){
		
		UsersSession usersSession  = (UsersSession)session.getAttribute(SessionConstant.SESSION_USER);
		usersSession.setLogin(false);
		TUsers guest = tUsersService.queryById(TUsersConstant.USER_GUEST_ID);
		usersSession.settUsers(guest);
		session.setAttribute(SessionConstant.SESSION_USER, usersSession);
		CookieUtil.removeCookie(response, CookieConstant.COOKIE_USER_KEY);
		return "user/loginInit";
	}
	
	
	@RequestMapping(value="/findPwd",method = { RequestMethod.GET})
	public String findPwd(){
		return "user/findPwd";
	}
	
	//保存新密码 
	@ResponseBody
	@RequestMapping(value = "/saveUserPwd", method = { RequestMethod.GET, RequestMethod.POST })
	public Map<String,Object> saveUserPwd( Model model,HttpSession session,TUsers tUsers,String verifycode,Integer step) {
		//手机号邮箱都应支持注册，但目前只支持邮箱
		Map<String,Object> mapResult = new HashMap<String,Object>();
		TUserActive  tUserActive = null ;
		if(step==1){
			mapResult.put("step",2);
			final int CODE_ERROR_IDENTITY = 401;
			if (StringUtils.isBlank(verifycode) || verifycode.length() != 6) {
				mapResult.put("code",CODE_ERROR_IDENTITY);
				mapResult.put("desc", "验证码错误!");
				return mapResult;
			}else{
				tUserActive =  tUserActiveService.queryLastByEmail(tUsers.getUserName());
				if( tUserActive == null){
					mapResult.put("code",CODE_ERROR_IDENTITY);
					mapResult.put("desc", "验证码错误!");
					return mapResult;
				}else{
					if(tUserActive.getVcode().equals(verifycode)){
						//判断是否过期 目前三十分钟过期
						if (System.currentTimeMillis() - tUserActive.getCreateTime().getTime() > 30 * 60 * 1000){
							//验证码过期
							mapResult.put("code",CODE_ERROR_IDENTITY);
							mapResult.put("desc", "验证码过期!");
							return mapResult;
						}
					}else{
						mapResult.put("code",CODE_ERROR_IDENTITY);
						mapResult.put("desc", "验证码错误!");
						return mapResult;
					}
				}
			};
			TUsers user = tUsersService.queryByLoginName(tUsers.getUserName());
			if(user != null){
				mapResult.put("code",HttpStatusCode.CODE_SUCCESS);
				mapResult.put("userId", user.getUserId());
				return mapResult;
			}else{
				mapResult.put("code",HttpStatusCode.CODE_ERROR);
				mapResult.put("desc", "用户名错误。");
				return mapResult;
			}
		}
		if(step==2){
			mapResult.put("step",3);
			String passwordMd5 = MD5.encodeStr(tUsers.getUserPassword());
			tUsers.setUserPassword(passwordMd5);
			tUsersService.updateByIdSelective(tUsers);
		}
		if(step==3){
			mapResult.put("step",3);
		}
		mapResult.put("code",HttpStatusCode.CODE_SUCCESS);
		return mapResult;
	}
}
